package com.leetcodehot.problems;

import java.util.ArrayList;
import java.util.List;

public class problems113 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    private final List<List<Integer>> ans = new ArrayList<>();
    private final List<Integer> path = new ArrayList<>();
    private int sum = 0;

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        dfs(root, targetSum);
        return ans;
    }

    private void dfs(TreeNode root, int targetSum) {
        if (root == null) return;
        sum += root.val;
        path.add(root.val);
        if (sum == targetSum && root.left == null && root.right == null) {
            ans.add(new ArrayList<>(path));
            //这里不应该return 需要注意看下是否return的时候能够处理好当前的元素
            //return;
        }
        dfs(root.left, targetSum);
        dfs(root.right, targetSum);
        path.remove(path.size() - 1);
        sum -= root.val;
    }
}
